package com.beans.secritys;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;

/**
 * Created by admin on 2017/5/16.
 */
public class MoreBase64 {

    public String src = "面向对象编程，object-oriented！Base64 学习"; // 需要加密的原始字符串

    /**
     * JDK实现Base64编码
     */
    @Test
    public void testBase64JDK() {
        //如果这里没有出现sun的base64可以从Build Path中删除然后添加
        BASE64Encoder encoder = new BASE64Encoder();
        String encode = encoder.encode(src.getBytes());//编码
        System.out.println("JDK实现的base64编码：\t\t" + encode);

        BASE64Decoder decoder = new BASE64Decoder();
        String decode = null;//解码
        try {
            decode = new String(decoder.decodeBuffer(encode));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("JDK实现的base64解码：\t\t" + decode);
    }

    /**
     * Apache的 Commons Codec实现base64编码
     */
    @Test
    public void commonsCodecBase64() {
        byte[] encodeBytes = Base64.encodeBase64(src.getBytes());
        System.out.println("Commons Codec实现base64编码：\t" + new String(encodeBytes));

        byte[] decodeBytes = Base64.decodeBase64(encodeBytes);
        System.out.println("Commons Codec实现base64解码：\t" + new String(decodeBytes));
    }

    /**
     * Bouncy Castle实现base64编码
     */
    @Test
    public void bouncyCastleBase64() {
        byte[] encodeBytes = org.bouncycastle.util.encoders.Base64.encode(src.getBytes());
        System.out.println("Bouncy Castle实现base64编码：\t" + new String(encodeBytes));

        byte[] decodeBytes = org.bouncycastle.util.encoders.Base64.decode(encodeBytes);
        System.out.println("Bouncy Castle实现base64解码：\t" + new String(decodeBytes));
    }
}
